#/bin/bash -e
# should start in FABRIC_DEPLOY

source cluster_IP.conf

CUR_PATH=`pwd`

function redeploy_fabric() {
    # stop fabric-sdk for 4 orgs & start kafka containers
    for node in ${FABRIC_SDK_IP[@]}
    do
        ssh $node "
            source /etc/profile
            # remove fabric-sdk server
            fabric_sdk=\$(ps -ef | grep main | grep -v grep | awk '{print \$2}')
            for id in \$fabric_sdk
            do
                sudo kill \$id
            done
            cd $CUR_PATH/kafka
            git pull
            bash start.sh -i $node
        " &
    done
    wait
    # redeploy fabric
    ssh $FABRIC_DEPLOY "
        source /etc/profile
        cd $CUR_PATH
        ./deploy_fabric.sh
    "
    # start fabric-sdk for 4 orgs
    for ((i=0; i<${#FABRIC_SDK_IP[@]}; i++))
    do
        ssh ${FABRIC_SDK_IP[$i]} "
            source /etc/profile
            cd $CUR_PATH/fabric-sdk
            git pull
            bash hosts_config.sh
            nohup go run main.go -o $i -b ${FABRIC_SDK_IP[$i]}:${KAFKA_PORT} -t ${KAFKA_TOPIC} > $CUR_PATH/fabric_sdk.log 2>&1 &
        " &
    done
    wait
}


redeploy_fabric